package com.itheima.netty.c8;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.stream.ChunkedWriteHandler;

public class StaticHttpServer {

    static class Server{
        private String basePath;

        public Server(String basePath) {
            this.basePath = basePath;
        }

        public void start(){
            EventLoopGroup boss = new NioEventLoopGroup();
            EventLoopGroup work = new NioEventLoopGroup();
            try {
                ServerBootstrap serverBootstrap = new ServerBootstrap();
                serverBootstrap.group(boss,work).channel(NioServerSocketChannel.class)
                        .option(ChannelOption.SO_BACKLOG,1024)
                        .childOption(ChannelOption.SO_KEEPALIVE,true)
                        .childOption(ChannelOption.RCVBUF_ALLOCATOR,new AdaptiveRecvByteBufAllocator())
                        .childOption(ChannelOption.TCP_NODELAY,true)
                        .childHandler(new ChannelInitializer<NioSocketChannel>() {
                            @Override
                            protected void initChannel(NioSocketChannel ch) throws Exception {
                                ch.pipeline().addLast(new HttpServerCodec())
                                        .addLast(new ChunkedWriteHandler())
                                        .addLast(new HttpObjectAggregator(64*1024))
                                        .addLast(new MyHttpServerHandler1(Server.this.basePath));
                            }
                        });
                ChannelFuture future = serverBootstrap.bind(8080).sync();
                Channel channel = future.channel();
                channel.closeFuture().sync();
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                boss.shutdownGracefully();
                work.shutdownGracefully();
            }
        }
    }

    public static void main(String[] args) {
        String basePath = Server.class.getClassLoader().getResource("").getPath();
        // String basePath = "E:/新建文件夹";
        // String path = URLDecoder.decode(basePath);
        System.out.println(String.format("basePath:%s",basePath));
        Server server = new Server(basePath);
        server.start();
    }

}
